package cn.mayaslight.common.chain;

public abstract class IChain {
	
	private IChain thePreChain;
	private IChain theNextChain;
	
	public boolean exec() throws Exception{
		boolean doneThis = doThis();
		if(theNextChain != null){
			if(doneThis){
				doIfCompleteThis();
				return theNextChain.exec();
			}else{
				return false;
			}
		}else{
			if(doneThis){
				doIfCompleteThis();
				doIfCompleteAll();
				doFinal();
				if(thePreChain != null){
					thePreChain.doFinal();
				}
			}
			return doneThis;
		}
	}
	
	public abstract boolean doThis() throws Exception;
	
	public abstract void doIfCompleteThis() throws Exception;
	
	public abstract void doFinal() throws Exception;
	
	public abstract void doIfCompleteAll() throws Exception;
	
	public IChain setThePreChain(IChain thePreChain){
		this.thePreChain = thePreChain;
		return this;
	}
	
	public IChain setTheNextChain(IChain theNextChain){
		this.theNextChain = theNextChain.setThePreChain(this);
		return this;
	}
	
}
